package yxy.game.pm2.module.camptower;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.redisson.api.RMap;
import yxy.cherry.battle.module.Position;
import yxy.cherry.battle.module.record.FighterPosition;
import yxy.cherry.battle.module.record.FighterSide;
import yxy.cherry.battle.module.record.result.BattleResult;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.*;
import yxy.cherry.game.base.redis.RedisManager;
import yxy.cherry.game.base.redis.RedisType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.*;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.bean.task.TaskType;
import yxy.game.pm2.message.BattleMessage;
import yxy.game.pm2.message.CampTowerMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.battle.*;
import yxy.game.pm2.module.stat.StatHandle;
import yxy.game.pm2.module.task.TaskHandle;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName CampTowerHandle
 * @Author jingtao-zheng
 * @Date 2022/8/1 11:37
 * @Version 1.0
 **/
public class CampTowerHandle extends BattleModuleHandle {
    public CampTowerHandle() {
    }

    public CampTowerHandle(BattleType battleType) {
        this.battleType = battleType;
    }

    private BattleType battleType;//战斗类型
    final public static int battleExpireDay = 1;// 战斗数据过期时间（天）

    /**
     * 获取所有阵营塔结束时间
     */
    public static Map<String, DateTime> getAllCampTowerEndTime(Map<String, racetowerdate> campMap) {
        Map<String, DateTime> campTowerendTime = new HashMap<>();
        DateTime wei = getCampTowerEndTime(campMap, Constant.WEI_ID);
        DateTime shu = getCampTowerEndTime(campMap, Constant.SHU_ID);
        DateTime wu = getCampTowerEndTime(campMap, Constant.WU_ID);
        DateTime qun = getCampTowerEndTime(campMap, Constant.QUN_ID);
        campTowerendTime.put(Constant.WEI_ID, wei);
        campTowerendTime.put(Constant.SHU_ID, shu);
        campTowerendTime.put(Constant.WU_ID, wu);
        campTowerendTime.put(Constant.QUN_ID, qun);
        return campTowerendTime;
    }

    /**
     * 获取阵营塔塔结束时间
     *
     * @param campMap 配置表
     * @param type    阵营塔类型
     */
    public static DateTime getCampTowerEndTime(Map<String, racetowerdate> campMap, String type) {
        //获取阵营塔配置表
        racetowerdate racetowerdate = campMap.get(type);
        String condition = racetowerdate.getCondition();
        String[] split = condition.trim().split(",");
        //获取魏国塔开放时间
        List<Integer> days = Arrays
                .stream(split)
                .map(_day -> Integer.parseInt(_day))
                .collect(Collectors.toList());
        //获取当前时间,并计算是星期几
        DateTime now = DateTime.now();
        int dayOfWeek = now.getDayOfWeek();
        boolean contains = days.contains(dayOfWeek);
        if (!contains) {
            //没开启活动--计算是前多少天结束
            int recentEndTime = getBeforeEndTime(days, dayOfWeek);
            //计算活动结束时间
            DateTime dateTime = now.plusDays(1);
            dateTime = dateTime.minusDays(recentEndTime);
            String formatTime = dateTime.toString("yyyy-MM-dd");
            DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd");
            dateTime = DateTime.parse(formatTime, format);
            return dateTime;
        } else {
            //活动开启--计算后多少天结束
            int afterEndTime = getAfterEndTime(days, dayOfWeek);
            //计算活动结束时间
            //DateTime dateTime = now.plusDays(1);
            DateTime dateTime = now.plusDays(afterEndTime);
            String formatTime = dateTime.toString("yyyy-MM-dd");
            DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd");
            dateTime = DateTime.parse(formatTime, format);
            return dateTime;
        }

    }

    /**
     * 判断该阵营塔是否结束
     *
     * @param type 阵营塔类型
     */
    public static boolean isFinish(int type) {
        Map<String, racetowerdate> campMap = DataCenter.getAllData(racetowerdate.class);
        //获取阵营塔配置表
        String realType = Constant.matchType(type);
        racetowerdate racetowerdate = campMap.get(realType);
        String condition = racetowerdate.getCondition();
        String[] split = condition.trim().split(",");
        //获取魏国塔开放时间
        List<Integer> days = Arrays
                .stream(split)
                .map(_day -> Integer.parseInt(_day))
                .collect(Collectors.toList());
        //获取当前时间,并计算是星期几
        DateTime now = DateTime.now();
        int dayOfWeek = now.getDayOfWeek();
        boolean contains = days.contains(dayOfWeek);
        if (!contains) {
            return false;//活动未开启
        } else {
            return true;//活动开启
        }
    }

    /**
     * 前多少天结束
     *
     * @param dayOfWeek 星期几
     */
    private static int getBeforeEndTime(List<Integer> days, int dayOfWeek) {
        int week = 0;
        int result = 0;
        //如果当前时间是星期一,就特殊处理
        if (dayOfWeek == 1) {
            week = 7;
        } else {
            week = dayOfWeek - 1;
        }
        //反推最近结束时间
        for (int i = week, j = 1; i >= 1; i--, j++) {
            if (days.contains(i) || i == 1) {
                result = j;
                break;
            }
        }
        return result;
    }

    /**
     * 后多少天结束
     *
     * @param dayOfWeek 星期几
     */
    private static int getAfterEndTime(List<Integer> days, int dayOfWeek) {
        int week = 0;
        int result = 0;
        //如果当前时间是星期天,就特殊处理
        if (dayOfWeek == 7) {
            week = 1;
        } else {
            week = dayOfWeek + 1;
        }
        //反推最近结束时间
        for (int i = week, j = 1; i <= 7; i++, j++) {
            if (!days.contains(i) || i == 7) {
                result = j;
                break;
            }
        }
        return result;
    }

    @Override
    protected String code() {
        return battleType.name();
    }

    /**
     * 判断是否还在战斗
     */
    public boolean isBattling(String playerCode) {
        BattleModule module = BattleModule.get(playerCode, code());
        if (module == null) {
            return false;
        }
        return isBattling(module);
    }

    public BattleMessage.BattleResponse battleResponse(String playerCode, int floor, boolean first, int type) throws Exception {
        BattleHandle battleHandle = new BattleHandle();

        BattleModule battleModule = createBattleModule(playerCode, floor, first, type);

        return battleHandle.battleResponse(battleModule);
    }

    private BattleModule createBattleModule(String playerCode, int floor, boolean first, int type) {
        BattleHandle battleHandle = new BattleHandle();

        BattleModule battleModule = BattleModule.create(playerCode);
        BattleType battleType = matchType(type);
        battleModule.setType(battleType);
        battleModule.setCode(code());

        // 玩家的team
        Format.FormatType formatType = matchFormatType(type);
        TeamModule teamA = battleHandle.teamPlayer(playerCode, formatType);
        battleModule.setTeamA(teamA);

        // 阵营塔敌方阵容
        TeamModule teamB = teamTower(floor,type);
        battleModule.setTeamB(teamB);

        battleModule.setSettlement(SettlementCampTower.create(playerCode, floor, first, type));


        battleModule.set(battleExpireDay);

        return battleModule;
    }


    public TeamModule teamTower(int floor,int type) {
        if(type == Constant.WEI){
            return teamWeiTower(floor);
        }
        if(type == Constant.SHU){
            return teamShuTower(floor);
        }
        if(type == Constant.WU){
            return teamWuTower(floor);
        }
        if(type == Constant.QUN){
            return teamQunTower(floor);
        }
        return null;
    }

    private TeamModule teamWeiTower(int floor){
        TeamModule team = new TeamModule();
        raceweitower _towerdata = DataCenter.getData(floor, raceweitower.class);
        ArrayList<FighterModule> fighterModules = getWeiFighterModuleList(floor);

        //战力
        long totalPower = 0;
        //主将 id
        int mainId = 0;
        // 武将
        for (int i = 0; i < _towerdata.getHeroid().length; i++) {
            Position position = Position.forValue(i + 1);
            int heroid = _towerdata.getHeroid()[i];
            if (heroid == -1) continue;
            FighterModule fighterModule = fighterModules.get(i);
            team.addfighter(position, fighterModule);
            totalPower += fighterModule.getTotalPower();
            if(i==4){
                mainId = heroid;
            }
        }
        // 神器
        WeaponModule weapon = WeaponModule.create(_towerdata.getWeapondataid(), _towerdata.getWeaponlv(), 0, 0, _towerdata.getWeaponskilllv());
        team.setWeapon(weapon);

        // 信息
        herodata _herodata = DataCenter.getData(mainId, herodata.class);
        team.setName(_herodata.getName());
        int i = mainId / 100;
        team.setHead(i);
        team.setPower(totalPower);

        return team;
    }

    private TeamModule teamShuTower(int floor){
        TeamModule team = new TeamModule();
        raceshutower _towerdata = DataCenter.getData(floor, raceshutower.class);
        ArrayList<FighterModule> fighterModules = getShuFighterModuleList(floor);

        //战力
        long totalPower = 0;
        //主将 id
        int mainId = 0;

        // 武将
        for (int i = 0; i < _towerdata.getHeroid().length; i++) {
            Position position = Position.forValue(i + 1);
            int heroid = _towerdata.getHeroid()[i];
            if (heroid == -1) continue;
            FighterModule fighterModule = fighterModules.get(i);
            team.addfighter(position, fighterModule);
            totalPower += fighterModule.getTotalPower();
            if(i==4){
                mainId = heroid;
            }
        }
        // 神器
        WeaponModule weapon = WeaponModule.create(_towerdata.getWeapondataid(), _towerdata.getWeaponlv(), 0, 0, _towerdata.getWeaponskilllv());
        team.setWeapon(weapon);

        // 信息
        herodata _herodata = DataCenter.getData(mainId, herodata.class);
        team.setName(_herodata.getName());
        int i = mainId / 100;
        team.setHead(i);
        team.setPower(totalPower);

        return team;
    }

    private TeamModule teamWuTower(int floor){
        TeamModule team = new TeamModule();
        racewutower _towerdata = DataCenter.getData(floor, racewutower.class);
        ArrayList<FighterModule> fighterModules = getWuFighterModuleList(floor);

        //战力
        long totalPower = 0;
        //主将 id
        int mainId = 0;

        // 武将
        for (int i = 0; i < _towerdata.getHeroid().length; i++) {
            Position position = Position.forValue(i + 1);
            int heroid = _towerdata.getHeroid()[i];
            if (heroid == -1) continue;
            FighterModule fighterModule = fighterModules.get(i);
            team.addfighter(position, fighterModule);
            totalPower += fighterModule.getTotalPower();
            if(i==4){
                mainId = heroid;
            }
        }
        // 神器
        WeaponModule weapon = WeaponModule.create(_towerdata.getWeapondataid(), _towerdata.getWeaponlv(), 0, 0, _towerdata.getWeaponskilllv());
        team.setWeapon(weapon);

        // 信息
        herodata _herodata = DataCenter.getData(mainId, herodata.class);
        team.setName(_herodata.getName());
        int i = mainId / 100;
        team.setHead(i);
        team.setPower(totalPower);

        return team;
    }

    private TeamModule teamQunTower(int floor){
        TeamModule team = new TeamModule();
        racequntower _towerdata = DataCenter.getData(floor, racequntower.class);
        ArrayList<FighterModule> fighterModules = getQunFighterModuleList(floor);

        //战力
        long totalPower = 0;
        //主将 id
        int mainId = 0;

        // 武将
        for (int i = 0; i < _towerdata.getHeroid().length; i++) {
            Position position = Position.forValue(i + 1);
            int heroid = _towerdata.getHeroid()[i];
            if (heroid == -1) continue;
            FighterModule fighterModule = fighterModules.get(i);
            team.addfighter(position, fighterModule);
            totalPower += fighterModule.getTotalPower();
            if(i==4){
                mainId = heroid;
            }
        }
        // 神器
        WeaponModule weapon = WeaponModule.create(_towerdata.getWeapondataid(), _towerdata.getWeaponlv(), 0, 0, _towerdata.getWeaponskilllv());
        team.setWeapon(weapon);

        // 信息
        herodata _herodata = DataCenter.getData(mainId, herodata.class);
        team.setName(_herodata.getName());
        int i = mainId / 100;
        team.setHead(i);
        team.setPower(totalPower);

        return team;
    }


    //获取内存怪物战力属性
    public ArrayList<FighterModule> getFighterModuleList(int floor) {
        RMap<String, ArrayList<FighterModule>> rMap = RedisManager.getInstance().getConnection(RedisType.REDIS_DATA).client().getMap("INIT:tower");
        JSONArray arrary = (JSONArray) JSONArray.toJSON(rMap.get(String.valueOf(floor)));
        ArrayList<FighterModule> fighterModules = JSON.parseObject(arrary.toString(), new TypeReference<ArrayList<FighterModule>>() {
        });
        return fighterModules;
    }

    //获取魏国塔内存怪物战力属性
    public ArrayList<FighterModule> getWeiFighterModuleList(int floor) {
        RMap<String, ArrayList<FighterModule>> rMap = RedisManager.getInstance().getConnection(RedisType.REDIS_DATA).client().getMap("INIT:campweitower");
        JSONArray arrary = (JSONArray) JSONArray.toJSON(rMap.get(String.valueOf(floor)));
        ArrayList<FighterModule> fighterModules = JSON.parseObject(arrary.toString(), new TypeReference<ArrayList<FighterModule>>() {
        });
        return fighterModules;
    }

    //获取蜀国塔内存怪物战力属性
    public ArrayList<FighterModule> getShuFighterModuleList(int floor) {
        RMap<String, ArrayList<FighterModule>> rMap = RedisManager.getInstance().getConnection(RedisType.REDIS_DATA).client().getMap("INIT:campshutower");
        JSONArray arrary = (JSONArray) JSONArray.toJSON(rMap.get(String.valueOf(floor)));
        ArrayList<FighterModule> fighterModules = JSON.parseObject(arrary.toString(), new TypeReference<ArrayList<FighterModule>>() {
        });
        return fighterModules;
    }

    //获取吴国塔内存怪物战力属性
    public ArrayList<FighterModule> getWuFighterModuleList(int floor) {
        RMap<String, ArrayList<FighterModule>> rMap = RedisManager.getInstance().getConnection(RedisType.REDIS_DATA).client().getMap("INIT:campwutower");
        JSONArray arrary = (JSONArray) JSONArray.toJSON(rMap.get(String.valueOf(floor)));
        ArrayList<FighterModule> fighterModules = JSON.parseObject(arrary.toString(), new TypeReference<ArrayList<FighterModule>>() {
        });
        return fighterModules;
    }

    //获取群国塔内存怪物战力属性
    public ArrayList<FighterModule> getQunFighterModuleList(int floor) {
        RMap<String, ArrayList<FighterModule>> rMap = RedisManager.getInstance().getConnection(RedisType.REDIS_DATA).client().getMap("INIT:campquntower");
        JSONArray arrary = (JSONArray) JSONArray.toJSON(rMap.get(String.valueOf(floor)));
        ArrayList<FighterModule> fighterModules = JSON.parseObject(arrary.toString(), new TypeReference<ArrayList<FighterModule>>() {
        });
        return fighterModules;
    }


    //返回战斗录像
    public BattleMessage.BattleExecuteResponse battleResponseExecute(String playerCode, BattleMessage.BattleExecuteRequest request, int type) throws Exception {
        //获取层数
        BattleModule battleModule = BattleModule.get(playerCode, code());
        //获取阵营塔结算
        int floor = ((SettlementCampTower) battleModule.getSettlement()).getFloor();
        CampTowerModule towerModule = CampTowerModule.get(playerCode);
        try {
            if (towerModule.tryLock()) {
                int[] angersTeamA = null;
                if (request != null) {
                    List<BattleMessage.FighterInfo> fighterInfos = request.getFormatList();
                    ArrayList<BattleMessage.FighterInfo> fighterInfosTeamA = new ArrayList<>();
                    for (BattleMessage.FighterInfo fighterInfo : fighterInfos) {
                        FighterPosition fp = FighterPosition.forNumber(fighterInfo.getPosition().getNumber());
                        if (fp.getSide().equals(FighterSide.LEFT)) {
                            fighterInfosTeamA.add(fighterInfo);
                        }
                    }
                    angersTeamA = new BattleHandle().angersFromFormatList(fighterInfosTeamA);
                }
                towerModule.setAngers(angersTeamA);
                towerModule.set();
            }
        } catch (Exception e) {
        } finally {
            towerModule.unlock();
        }
        BattleMessage.BattleExecuteResponse response = new BattleHandle().battleResponseExecute(battleModule, towerModule.getAngers(), null);
        battleModule = BattleModule.get(playerCode, code());
        SettlementCampTower settlement = (SettlementCampTower) battleModule.getSettlement();
        //计算星星数
        BattleMessage.BattlePlayBack playback = response.getPlayback();
        List<BattleMessage.FighterResult> statisticList = playback.getStatisticList();
        //计算左边阵营的存活武将数量
        long count = statisticList
                .stream()
                .filter(_FighterResult -> _FighterResult.getHpc() > 0)
                .filter(_FighterResult ->
                        _FighterResult.getPosition().getNumber() == Constant.FUL
                                ||
                                _FighterResult.getPosition().getNumber() == Constant.FML
                                ||
                                _FighterResult.getPosition().getNumber() == Constant.FDL
                                ||
                                _FighterResult.getPosition().getNumber() == Constant.BUL
                                ||
                                _FighterResult.getPosition().getNumber() == Constant.BML
                                ||
                                _FighterResult.getPosition().getNumber() == Constant.BDL
                ).count();
        int starnum = 0;
        if (count >= 4) {
            starnum = 3;
        } else if (count == 3) {
            starnum = 2;
        } else {
            starnum = 1;
        }
        if (starnum != 0) {
            settlement.setStarnum(starnum);
            battleModule.setSettlement(settlement);
            battleModule.set(1);
        }
        // 判断阵营塔层记录
        if (battleModule.getBattleResult().equals(BattleResult.LEFT_WIN)) {
            CampTowerFloorModule floorModule = CampTowerFloorModule.get(playerCode, floor, type);
            if (floorModule != null) {
                floorModule.record(playerCode, battleModule, type);
                TaskType taskType = matchTaskType(type);
                TaskHandle.handle(playerCode, taskType, 1);
            }
        }

        return response;
    }

    /**
     * 封装层消息
     * 最短回合数记录
     * 最低战力通过记录
     */
    public void packTowerFloor(String playerCode, int floor, CampTowerMessage.CampTowerFloorResponse.Builder response, int type) {
        CampTowerFloorModule floorModule = CampTowerFloorModule.get(playerCode, floor, type);
        if (floorModule == null) {
            return;
        }
        try {
            //最短回合数记录
            response.setBestTime(packTowerFloorBest(floorModule.getBestRound()));
        } catch (Exception e) {
        }
        try {
            //最低战力通过记录
            response.setBestPower(packTowerFloorBest(floorModule.getBestPower()));
        } catch (Exception e) {
        }
    }

    private CampTowerMessage.TowerFloorBest packTowerFloorBest(CampTowerFloorRecord bestRecord) {
        PlayerBean playerBean = PlayerBean.get(bestRecord.getPlayerCode());
        CampTowerMessage.TowerFloorBest.Builder builder = CampTowerMessage.TowerFloorBest.newBuilder();
        builder.setPlayerCode(playerBean.getCode());
        builder.setNickname(playerBean.getName());
        builder.setHead(playerBean.getHead());
        builder.setHeadFrame(playerBean.getHeadframe());

        builder.setBattleCode(bestRecord.getRecordCode());
        builder.setValue(bestRecord.getValue());
        return builder.build();
    }

    public Boolean nextFloor(String playerCode, int battlefloor, int type, int starNum) {
        CampTowerModule module = CampTowerModule.get(playerCode);
        try {
            if (module.tryLock()) {
                if (type == Constant.WEI && DataCenter.getData(battlefloor, raceweitower.class) != null) {
                    module.updateStarAndChapterAndFloor(battlefloor, type, starNum);
                    // 记录排行榜
                    RankWeiCampTower.getRank(playerCode).put(playerCode, battlefloor);
                    StatHandle.stat_关卡统计(playerCode, CCReason.阵营塔, battlefloor);
                }
                if (type == Constant.SHU && DataCenter.getData(battlefloor, raceshutower.class) != null) {
                    module.updateStarAndChapterAndFloor(battlefloor, type, starNum);
                    // 记录排行榜
                    RankShuCampTower.getRank(playerCode).put(playerCode, battlefloor);
                    StatHandle.stat_关卡统计(playerCode, CCReason.阵营塔, battlefloor);
                }
                if (type == Constant.WU && DataCenter.getData(battlefloor, racewutower.class) != null) {
                    module.updateStarAndChapterAndFloor(battlefloor, type, starNum);
                    // 记录排行榜
                    RankWuCampTower.getRank(playerCode).put(playerCode, battlefloor);
                    StatHandle.stat_关卡统计(playerCode, CCReason.阵营塔, battlefloor);
                }
                if (type == Constant.QUN && DataCenter.getData(battlefloor, racequntower.class) != null) {
                    module.updateStarAndChapterAndFloor(battlefloor, type, starNum);
                    // 记录排行榜
                    RankQunCampTower.getRank(playerCode).put(playerCode, battlefloor);
                    StatHandle.stat_关卡统计(playerCode, CCReason.阵营塔, battlefloor);
                }
                module.set();
            }
        } catch (Exception e) {
            return false;
        } finally {
            module.unlock();
        }
        return true;
    }

    /**
     * 检测阵营是否满足要求
     *
     * @param type  阵营类型
     * @param floor 层数
     */
    public static boolean checkCamp(ArrayList<String> campList, int type, int floor, String playerCode) {
        int[] campLimit = matchCampLimit(type, floor);
        int limit1 = campLimit[0];//限制条件1
        int limit2 = campLimit[1];//限制条件2
        int temp = 0;
        List<String> collect = campList.stream().filter(_camp -> _camp != null).collect(Collectors.toList());
        for (String heroCode : collect) {
            Hero hero = Hero.get(playerCode, heroCode);
            if (hero == null){
                return false;
            }
            int dataId = hero.getDataId();
            herodata data = DataCenter.getData(dataId, herodata.class);
            int power = data.getPower();
            if (limit1 != power && limit2 != power) {
                return false;
            }
            if(limit2 == power){
                temp ++;
            }
        }
        //限制2不能超过3个
        if(temp>3){
            return false;
        }
        return true;
    }


    public static Collection<Currency> floorRewards(int floor, boolean first, int type) {
        ArrayList<Currency> rewards = new ArrayList<>();
        if (type == Constant.WEI) {
            raceweitower towerdata = DataCenter.getData(floor, raceweitower.class);
            if (towerdata == null) {
                return rewards;
            }
            rewards.addAll(Currency.create(towerdata.getRewardtype(), towerdata.getRewardid(), towerdata.getRewardnum()));
            if (first) {
                rewards.addAll(Currency.create(towerdata.getFirsttype(), towerdata.getFirstid(), towerdata.getFirstnum()));
            }
            return rewards;
        }
        if (type == Constant.SHU) {
            raceshutower towerdata = DataCenter.getData(floor, raceshutower.class);
            if (towerdata == null) {
                return rewards;
            }
            rewards.addAll(Currency.create(towerdata.getRewardtype(), towerdata.getRewardid(), towerdata.getRewardnum()));
            if (first) {
                rewards.addAll(Currency.create(towerdata.getFirsttype(), towerdata.getFirstid(), towerdata.getFirstnum()));
            }
            return rewards;
        }
        if (type == Constant.WU) {
            racewutower towerdata = DataCenter.getData(floor, racewutower.class);
            if (towerdata == null) {
                return rewards;
            }
            rewards.addAll(Currency.create(towerdata.getRewardtype(), towerdata.getRewardid(), towerdata.getRewardnum()));
            if (first) {
                rewards.addAll(Currency.create(towerdata.getFirsttype(), towerdata.getFirstid(), towerdata.getFirstnum()));
            }
            return rewards;
        }
        if (type == Constant.QUN) {
            racequntower towerdata = DataCenter.getData(floor, racequntower.class);
            if (towerdata == null) {
                return rewards;
            }
            rewards.addAll(Currency.create(towerdata.getRewardtype(), towerdata.getRewardid(), towerdata.getRewardnum()));
            if (first) {
                rewards.addAll(Currency.create(towerdata.getFirsttype(), towerdata.getFirstid(), towerdata.getFirstnum()));
            }
            return rewards;
        }
        return null;
    }

    /**
     * 阵营塔爬塔奖励
     * @param playerCode
     * @param id
     * @param response
     * @return
     */
    public Result levelReward(String playerCode, int id, CampTowerMessage.CampTowerStageTargetReceiveResponse.Builder response,int type) {
        CampTowerModule module = CampTowerModule.get(playerCode);
        try {
            if (module.tryLock()) {
                for (int i = 0, size =module.getLevelReward().get(type).size(); i < size; i++) {
                    int levelRewardId = module.getLevelReward().get(type).get(i);
                    if (levelRewardId == id) {
                        return Result.TowerBonusRewarded;// 这个奖励已经领过
                    }
                }

                towerlvreward _levelreward = DataCenter.getData(id, towerlvreward.class);
                module.getLevelReward().get(type).add(_levelreward.getId());
                //保存以领取的奖励-前置保护
                module.set();
                //发奖
                Collection<Currency> rewards = Currency.create(_levelreward.getRewardtype(), _levelreward.getRewardid(), _levelreward.getRewardnum());
                new CurrencyHandle().addCurrency(playerCode, CCReason.阵营塔, rewards);
                response.addAllRewards(new CurrencyHandle().packItems(rewards));
                for (Integer levelRewardId : module.getLevelReward().get(type)) {
                    response.addBox(levelRewardId);
                }

                return Result.Success;
            }
        } catch (Exception e) {
        } finally {
            module.unlock();
        }
        return Result.DataError;
    }

    /**
     * 阵营塔爬塔星星奖励
     * @param playerCode
     * @param id
     * @param response
     * @return
     */
    public Result starReward(String playerCode, int id, CampTowerMessage.CampTowerStarTargetReceiveResponse.Builder response,int type) {
        CampTowerModule module = CampTowerModule.get(playerCode);
        try {
            if (module.tryLock()) {
                for (int i = 0, size =module.getStarReward().get(type).size(); i < size; i++) {
                    int starRewardId = module.getStarReward().get(type).get(i);
                    if (starRewardId == id) {
                        return Result.TowerBonusRewarded;// 这个奖励已经领过
                    }
                }

                racestarreward _starreward = DataCenter.getData(id, racestarreward.class);
                module.getStarReward().get(type).add(_starreward.getId());
                //保存以领取的奖励-前置保护
                module.set();
                //发奖
                Collection<Currency> rewards = Currency.create(_starreward.getRewardtype(), _starreward.getRewardid(), _starreward.getRewardnum());
                new CurrencyHandle().addCurrency(playerCode, CCReason.阵营塔, rewards);
                response.addAllRewards(new CurrencyHandle().packItems(rewards));
                for (Integer starRewardId : module.getStarReward().get(type)) {
                    response.addBox(starRewardId);
                }

                return Result.Success;
            }
        } catch (Exception e) {
        } finally {
            module.unlock();
        }
        return Result.DataError;
    }



    public static TaskType matchTaskType(int type) {
        if (type == Constant.WEI) {
            return TaskType.统计型_魏国塔_挑战_次数;
        }
        if (type == Constant.SHU) {
            return TaskType.统计型_蜀国塔_挑战_次数;
        }
        if (type == Constant.WU) {
            return TaskType.统计型_吴国塔_挑战_次数;
        }
        if (type == Constant.QUN) {
            return TaskType.统计型_群国塔_挑战_次数;
        }
        return null;
    }

    public static TaskType matchTaskType2(int type) {
        if (type == Constant.WEI) {
            return TaskType.指标型_魏国塔_关卡_达到;
        }
        if (type == Constant.SHU) {
            return TaskType.指标型_蜀国塔_关卡_达到;
        }
        if (type == Constant.WU) {
            return TaskType.指标型_吴国塔_关卡_达到;
        }
        if (type == Constant.QUN) {
            return TaskType.指标型_群国塔_关卡_达到;
        }
        return null;
    }

    public static BattleType matchBattleType(int key) {
        if (key == Constant.WEI) {
            return BattleType.WEI_TOWER;
        }
        if (key == Constant.SHU) {
            return BattleType.SHU_TOWER;
        }
        if (key == Constant.WU) {
            return BattleType.WU_TOWER;
        }
        if (key == Constant.QUN) {
            return BattleType.QUN_TOWER;
        }
        return null;
    }

    public static String matchRacetowerdateType(int key) {
        if (key == Constant.WEI) {
            return Constant.WEI_ID;
        }
        if (key == Constant.SHU) {
            return Constant.SHU_ID;
        }
        if (key == Constant.WU) {
            return Constant.WU_ID;
        }
        if (key == Constant.QUN) {
            return Constant.QUN_ID;
        }
        return null;
    }

    public static int matchRacetowerdateTypeRe(String key) {
        if (key.equals(Constant.WEI_ID)) {
            return Constant.WEI;
        }
        if (key.equals(Constant.SHU_ID)) {
            return Constant.SHU;
        }
        if (key.equals(Constant.WU_ID)) {
            return Constant.WU;
        }
        if (key.equals(Constant.QUN_ID)) {
            return Constant.QUN;
        }
        return 0;
    }

    public static int matchRankIndex(int key) {
        if (key == Constant.WEI) {
            return Constant.WEI_INDEX;
        }
        if (key == Constant.SHU) {
            return Constant.SHU_INDEX;
        }
        if (key == Constant.WU) {
            return Constant.WU_INDEX;
        }
        if (key == Constant.QUN) {
            return Constant.QUN_INDEX;
        }
        return -1;
    }

    /**
     * 匹配阵营塔类型
     *
     * @param key
     */
    private BattleType matchType(int key) {
        if (key == Constant.WEI) {
            return BattleType.WEI_TOWER;
        }
        if (key == Constant.SHU) {
            return BattleType.SHU_TOWER;
        }
        if (key == Constant.WU) {
            return BattleType.WU_TOWER;
        }
        if (key == Constant.QUN) {
            return BattleType.QUN_TOWER;
        }
        return null;
    }

    /**
     * 匹配阵营塔阵容类型
     *
     * @param key
     */
    public static Format.FormatType matchFormatType(int key) {
        if (key == Constant.WEI) {
            return Format.FormatType.魏国塔;
        }
        if (key == Constant.SHU) {
            return Format.FormatType.蜀国塔;
        }
        if (key == Constant.WU) {
            return Format.FormatType.吴国塔;
        }
        if (key == Constant.QUN) {
            return Format.FormatType.群国塔;
        }
        return null;
    }

    //匹配阵容限制
    public static int[] matchCampLimit(int key, int floor) {
        if (key == Constant.WEI) {
            raceweitower data = DataCenter.getData(floor, raceweitower.class);
            return data.getLineuplimit();
        }
        if (key == Constant.SHU) {
            raceshutower data = DataCenter.getData(floor, raceshutower.class);
            return data.getLineuplimit();
        }
        if (key == Constant.WU) {
            racewutower data = DataCenter.getData(floor, racewutower.class);
            return data.getLineuplimit();
        }
        if (key == Constant.QUN) {
            racequntower data = DataCenter.getData(floor, racequntower.class);
            return data.getLineuplimit();
        }
        return null;
    }
}
